package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.elastic.SkuElasticModel;
import com.atguigu.gulimall.search.config.ElasticConfig;
import com.atguigu.gulimall.search.constant.ElasticConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author LiDeJie
 * @Create 2024/1/1 17:25
 * @Version 1.0
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    
    @Autowired
    RestHighLevelClient restHighLevelClient;
    
    /**
     * 商品上架
     */
    @Override
    public boolean productUpperStatus(List<SkuElasticModel> skuElasticModelList) {
        //创建索引、指定映射
        BulkRequest bulkRequest = new BulkRequest();
        skuElasticModelList.forEach(item -> {
            IndexRequest indexRequest = new IndexRequest(ElasticConstant.PRODUCT_INDEX);
            indexRequest.id(String.valueOf(item.getSkuId()));
            indexRequest.source(JSONObject.toJSONString(item), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        
        //添加文档
        BulkResponse response = null;
        try {
            response = restHighLevelClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            log.error("productUpperStatus field, request params: [{}], error: {}",JSONObject.toJSONString(response.getItems()), e.getMessage());
            e.printStackTrace();
        }
    
        //获取商品上架的Id集合
        List<String> indexIds = Arrays.stream(response.getItems()).map(result -> result.getId()).collect(Collectors.toList());
    
        //查看响应结果是否有错误
        boolean failures = response.hasFailures();
        //failures: true 表示批量上架数据有错误，否则没有错误
        if (failures) {
            log.error("商品上架错误, skuId: [{}]", JSONObject.toJSONString(indexIds));
        }
        return failures;
    }
}
